package com.spring.boot.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.spring.boot.entity.InOutNumCurve;
import com.spring.boot.entity.ProvinceCity;
import com.spring.boot.entity.Ranking;
import com.spring.boot.service.*;
import com.spring.boot.entity.InOutNum;
import com.spring.boot.vo.ProvinceVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.spring.boot.utils.MyUtils.*;

@Component
public class MyPipline implements Pipeline {
    private final static Logger log = LoggerFactory.getLogger(MyPipline.class);
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private CityService cityService;
    @Autowired
    private RankingService rankingService;
    @Autowired
    private InOutNumService inOutNumService;
    @Autowired
    private ChinaCityService chinaCityService;
    @Autowired
    private InOutNumCurveService inOutNumCurveService;

    @Override
    public void process(ResultItems resultItems, Task task) {
        //对不同页面不同处理
//        String domain = task.getSite().getDomain();
//        todo 这里的判断还需要完善，我觉得应该是根据task来判断，或者使用不同的pipeline来处理,而且url应该作为一个全局变量来使用，而不是哪里用到就复制粘贴过去
        Request request = resultItems.getRequest();
        String url = request.getUrl();
        CityId originCity = resultItems.get("originCity");
        if (url.equals("https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_aladin_banner&city=%E7%A6%8F%E5%BB%BA-%E7%A6%8F%E5%BB%BA")) {
            //保存省份数据
            ProvinceVo provinceVo = resultItems.get("provinceVo");
            provinceService.saveVo(provinceVo);
//        保存地级市信息
            List<ProvinceCity> citys = resultItems.get("citys");
            citys.removeIf(city -> city.getCity().equals("待确认"));
            for (ProvinceCity item : citys) {
                switch (item.getCity()) {
                    case "厦门":
                        item.setAdministrativeCode("350200");
                        item.setCreateTime(today());
                        item.setMark("350200" + today());
                        break;
                    case "南平":
                        item.setAdministrativeCode("350700");
                        item.setCreateTime(today());
                        item.setMark("350700" + today());
                        break;
                    case "莆田":
                        item.setAdministrativeCode("350300");
                        item.setCreateTime(today());
                        item.setMark("350300" + today());
                        break;
                    case "泉州":
                        item.setAdministrativeCode("350500");
                        item.setCreateTime(today());
                        item.setMark("350500" + today());
                        break;
                    case "漳州":
                        item.setAdministrativeCode("350600");
                        item.setCreateTime(today());
                        item.setMark("350600" + today());
                        break;
                    case "三明":
                        item.setAdministrativeCode("350400");
                        item.setCreateTime(today());
                        item.setMark("350400" + today());
                        break;
                    case "宁德":
                        item.setAdministrativeCode("350900");
                        item.setCreateTime(today());
                        item.setMark("350900" + today());
                        break;
                    case "龙岩":
                        item.setAdministrativeCode("350800");
                        item.setCreateTime(today());
                        item.setMark("350800" + today());
                        break;
                    case "福州":
                        item.setAdministrativeCode("350100");
                        item.setCreateTime(today());
                        item.setMark("350100" + today());
                        break;
                }
            }
            cityService.saveOrUpdateBatch(citys);
//       保存地级市新增确诊人数信息
            List<Ranking> rankings = new ArrayList<>();
            for (ProvinceCity item : citys) {
                String city = item.getCity();
                int onfirmedRelative = Integer.parseInt(item.getConfirmedRelative());
                rankings.add(new Ranking(city, onfirmedRelative));
            }
            rankingService.saveBatch(rankings);

//            保存全国市级数据
            JSONArray chinaCaseList = resultItems.get("chinaCaseList");
            chinaCityService.mySave(chinaCaseList);
        }
        else if (url.contains("move_in") && url.contains("cityrank")) {
            JSONArray inOutNum = resultItems.get("inOutNum");

            List<InOutNum> inOutNums = inOutNum.toJavaList(InOutNum.class);
            for (InOutNum item : inOutNums) {
                item.setType("in");
                item.setTargetCity(originCity.getCityName());
                item.setDate(StrUtil.subAfter(url, "&date=", true));
                item.setMark(originCity.getCityName() + item.getCityName() + "in" + StrUtil.subAfter(url, "&date=", true));
            }
            boolean isOK = inOutNumService.mySaveOrUpdateBatch(inOutNums);
//            if (isOK) {
//                log.info("前一百迁入城市入库", inOutNums);
//            }
        }
        else if (url.contains("move_out") && url.contains("cityrank")) {
            JSONArray inOutNum = resultItems.get("inOutNum");
            List<InOutNum> inOutNums = inOutNum.toJavaList(InOutNum.class);
            for (InOutNum item : inOutNums) {
                item.setType("out");
                item.setTargetCity(originCity.getCityName());
                item.setDate(StrUtil.subAfter(url, "&date=", true));
                item.setMark(originCity.getCityName() + item.getCityName() + "out" + StrUtil.subAfter(url, "&date=", true));
            }
            boolean isOK = inOutNumService.mySaveOrUpdateBatch(inOutNums);
//            if (isOK) {
//                log.info("前一百迁出城市入库", inOutNums);
//            }
        } else if (url.contains("move_in") && url.contains("historycurve")) {
            saveCurveData(resultItems);
        } else if (url.contains("move_out") && url.contains("historycurve")) {
            saveCurveData(resultItems);
        }
    }

    private void saveCurveData(ResultItems resultItems) {
        JSONObject historyCurve = resultItems.get("historyCurve");
        String type = resultItems.get("type");
        CityId sourceCity = resultItems.get("originCity");
        List<String> historyCurveKeys = getJsonKeys(historyCurve);
        for (String key : historyCurveKeys) {
            InOutNumCurve item = new InOutNumCurve();
            item.setCity(sourceCity.getCityName());
            item.setDate(key);
            item.setType(type);
            Object value = historyCurve.get(key);
            BigDecimal val = new BigDecimal(value.toString());
            item.setValue(val);
            item.setMark(sourceCity.getCityName() + type + key);
            boolean b = inOutNumCurveService.saveOrUpdate(item);
//            if (b){
//                System.out.println(sourceCity.getCityName() + "\t" + "历史迁徙指数入库");
//            } else {
//                System.out.println(sourceCity.getCityName() + "\t" + "历史迁徙指数入库异常！！！！");
//            }
        }
    }
}
